package com.semlab.client.app;

import java.util.logging.Logger;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.PlaceChangeEvent;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.place.shared.PlaceHistoryHandler;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.inject.Inject;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.semlab.client.app.gin.Injector;
import com.semlab.client.bundle.Resources;
import com.semlab.client.events.ClientLoginEvent;
import com.semlab.client.events.FBLoginEvent;
import com.semlab.client.fwk.Event;
import com.semlab.client.fwk.ShellWidget;
import com.semlab.client.fwk.Utils;
import com.semlab.client.fwk.ap.DefaultActivityRegistry;
import com.semlab.client.fwk.ap.Place;
import com.semlab.client.mvp.home.HomeMVP;
import com.semlab.client.proxy.ClientProxy;

public class Application {

    private static final Logger log = Logger.getLogger(Application.class.getName());


    public static final String WORKSPACE_CONTAINER_ID = "w";
    private final EventBus eventBus;
    private final PlaceController placeController;
    private final PlaceHistoryHandler placeHistoryHandler;
    private final DefaultActivityRegistry activityManager;
    private final ShellWidget shell;
    private static ClientProxy clientProxy;

    private Place defaultPlace = HomeMVP.place();

    @Inject
    public Application(EventBus eventBus, PlaceController placeController, ShellWidget shell,
                       DefaultActivityRegistry activityManager, PlaceHistoryHandler placeHistoryHandler) {
        this.eventBus = eventBus;
        this.placeController = placeController;
        this.activityManager = activityManager;
        this.placeHistoryHandler = placeHistoryHandler;
        this.shell = shell;
    }

    public void start() {
        log.fine("starting application result");
        Resources.INSTANCE.css().ensureInjected();

        init();

        placeHistoryHandler.handleCurrentHistory();

        /* Hide the loading... */
        Utils.removeWidget("loading");

        /* And show the user the shell */
        RootLayoutPanel.get().add(shell.asWidget());
    }

    private void init() {

        eventBus.addHandler(PlaceChangeEvent.TYPE, new PlaceChangeEvent.Handler() {
            @Override
            public void onPlaceChange(PlaceChangeEvent event) {
                if (event.getNewPlace() instanceof Place) {
                    Place thePlace = (Place) event.getNewPlace();
                    if (thePlace.getContainerId().equals(WORKSPACE_CONTAINER_ID)) {
//						log.fine("yes");
                    }
                }
            }
        });
        eventBus.addHandler(FBLoginEvent.TYPE, new Event.Handler<FBLoginEvent>() {
            @Override
            public void on(FBLoginEvent e) {
                if (e.getClient().getId() != null) {
                    log.fine(":: saving token in app:: token=" + e.getClient().getToken());
                    Injector.INSTANCE.getRequestFactory().clientRequest().login(e.getClient().getId(), e.getClient().getToken()).fire(new Receiver<ClientProxy>() {
                        @Override
                        public void onSuccess(ClientProxy response) {
                            clientProxy = response;
//							getClientProxy();
                            Injector.INSTANCE.getEventBus().fireEvent(new ClientLoginEvent(clientProxy));
                            GWT.log("logging in");
                        }
                    });
                } else {
                    log.fine("## login unsuccessful");
                }
            }
        });
        activityManager.registerContainer(WORKSPACE_CONTAINER_ID, shell.getInnerWidget());

//		GWT.setUncaughtExceptionHandler(new GWT.UncaughtExceptionHandler() {
//			public void onUncaughtException(Throwable e) {
////				Window.alert("Error global handler: " + e.getMessage());
//				log.severe(e.getMessage());
//			}
//		});


        activityManager.process();
        placeHistoryHandler.register(placeController, eventBus, defaultPlace);
    }

    public static ClientProxy getClientProxy() {
        return clientProxy;
    }

}
